package com.baizhi.cmfz.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.cmfz.entity.CmfzAdmin;
import com.baizhi.cmfz.entity.CmfzAdminRole;
import com.baizhi.cmfz.entity.CmfzBanner;
import com.baizhi.cmfz.mapper.CmfzAdminRoleMapper;
import com.baizhi.cmfz.service.CmfzAdminService;
import com.baizhi.cmfz.service.CmfzRoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/admin")
public class CmfzAdminController {

    @Autowired
    private CmfzAdminService as;
    @Autowired
    private CmfzAdminRoleMapper carm;

    /**
     * 验证码的获取
     */
    @RequestMapping("/getCaptcha")
    public String getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        //获取验证码图片并且设置大小
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 50);
        //获取正确答案
        String code = captcha.getCode();
        System.out.println("验证码答案是" + code);
        //将验证码的答案放在session中
        session.setAttribute("realCode", code);
        //通过流传递给页面
        ServletOutputStream out = response.getOutputStream();
        captcha.write(out);
        return null;
    }

    /**
     * 正常登录
     */

    @RequestMapping("/login")
    public String login(HttpSession session, String username, String password, String code) {
        //判断是否存在该管理员
        CmfzAdmin admin = as.selectByNameAndPwd(username, password);
        String realCode = (String) session.getAttribute("realCode");
        System.out.println(realCode);
        if (code.equals(realCode) && admin != null) {
            session.setAttribute("admin", admin);
            return "redirect:/main.jsp";
        } else {
            return "redirect:/login.jsp";
        }
    }

    /**
     * shiro登录
     */
    @RequestMapping("/shiroLogin")
    public String shiroLogin(String username, String password,String code,HttpSession session) {
        String realCode = (String) session.getAttribute("realCode");
        if (code.equals(realCode)){
            try {
                //封装到令牌中
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                //获取主体
                Subject subject = SecurityUtils.getSubject();
                //获取session shiro提供过了一个简单的方法
                //Session session = subject.getSession();
                //登录认证
                subject.login(token);
                log.debug("登录成功");
                //获取用户名
                String username1 = SecurityUtils.getSubject().getPrincipal().toString();
                session.setAttribute("admin", username1);
                return "redirect:/main.jsp";
            } catch (Exception e) {
                return "redirect:/login.jsp";
            }
        }else{
            log.info("验证码不正确");
            return "redirect:/login.jsp";
        }

    }


    /**
     * 注册
     */
    @RequestMapping("/addAdmin")
    @ResponseBody
    public void register(CmfzAdmin admin,Integer roleId) {
        log.info("username={}=========password={}",admin.getUsername(),admin.getUsername());
        as.insertAdmin(admin);
        log.info(admin.getId().toString());
        //添加管理员和角色的关系 在中间表中
        CmfzAdminRole cmfzAdminRole = new CmfzAdminRole(null, admin.getId(), roleId);
        carm.insert(cmfzAdminRole);
    }


    /**
     * 查询管理员
     */
    @RequestMapping("/selectAllAdmin")
    @ResponseBody
    public Map<String, Object> selectAllAdmin(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                              @RequestParam(value = "limit", defaultValue = "5") Integer limit) {

        //调用serive层写好的分页查询方法
        Page<CmfzAdmin> pi = as.selectAllByPage(page, limit);
        //改好layui需要的json格式
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", pi.getTotal());
        map.put("data", pi.getRecords());
        return map;
    }


    /**
     * 删除管理员
     */
    @RequestMapping("/deleteAdmin")
    @ResponseBody
    public void deleteAdmin(Integer id) {
        as.deleteAdmin(id);
    }

    /**
     * 修改管理员
     */
    @RequestMapping("/updateAdmin")
    @ResponseBody
    public void updateAdmin(CmfzAdmin admin) {
        as.updateAdmin(admin);
    }

    /**
     * 根据id查找管理员
     */
    @RequestMapping("/selectById")
    @ResponseBody
    public CmfzAdmin selectById(Integer id) {
        return as.selectById(id);
    }

    /**
     * 表连接查询管理员以及他的角色
     */
    @RequestMapping("/selectAdminAndRole")
    @ResponseBody
    public Map<String,Object> selectAdminAndRole(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                 @RequestParam(value = "limit", defaultValue = "5") Integer limit){
        //调用serive层写好的分页查询方法
        IPage<CmfzAdmin> pi = as.selectAdminAndRole(page, limit);
        //改好layui需要的json格式
        Map<String, Object> map = new HashMap<>();
        System.out.println();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", pi.getTotal());
        map.put("data", pi.getRecords());
        return map;
    }

}
